%% Author: maciek
%% Created: 16-04-2011
%% Description: TODO: Add description to iax_network
-module(iax_network).
-compile(export_all).
%%
%% Include files
%%

%%
%% Exported Functions
%%
-export([]).
-include("iax2_common.hrl").
%%
%% API Functions
%%
init() ->
	ets:new(iax_external_peers,[named_table,public]),
	ets:new(iax_dialogs,[named_table,public]),
	ets:new(iax_network_internal_peers, [named_table,public]),
	{ok,Socket} = gen_udp:open(14569, [inet,binary,{recbuf, 1500}]),
	MLPid =  spawn(?MODULE,main_loop,[Socket]),
	register(iax_network, MLPid),
	io:format("Main loop PID ~p~n", [MLPid]),
	gen_udp:controlling_process(Socket, MLPid),
	ets:insert(iax_network_internal_peers, {1,MLPid}),
	MLPid.
	

main_loop(Socket) ->
	receive	
		
			{send,IPaddr,Port,Msg} when is_binary(Msg)->
				%io:format("Sending msg To ~p:~p~n",[IPaddr,Port]),
				gen_udp:send(Socket, IPaddr, Port, Msg),
				main_loop(Socket);
			terminate ->
				io:format("Terminating MainLoop.... ~n"),
				terminate(Socket);
			{udp,Port,IpAddr,UDPPport,<<1:1,A:7,BinData/binary>>}   ->
				

				%io:format(">>>>>>>[[[[NETWORK]]]]>>>>>>Received FULLFRAME~n"),
				Packet=iax2_parser:decode_iax2_frame(<<1:1,A:7,BinData/binary>>),
				
				CallCName = call_controller:generate_server_name(Packet#fullframe.dstcallnumber,IpAddr,Port),
				
				call_controller:packet(CallCName,Packet),
				main_loop(Socket);
			{udp,Port,IpAddr,UDPPport,<<0:1,A:7,BinData/binary>>}   ->
				

				%io:format(">>>>>>>[[[[NETWORK]]]]>>>>>>Received MINIFRAME ~n"),
				%Packet=iax2_parser:decode_iax2_frame(Data),
				%io:format("Trying to decode : ~n=====================~n~p~n=====================~n",[Packet]),
				%CallCName = call_controller:generate_server_name(Packet#fullframe.dstcallnumber,IpAddr,Port),
				%io:format("Dispatching data to CallController ~p~n",[CallCName]),
				%call_controller:packet(CallCName,Packet),
				main_loop(Socket)
			
	end.
%%
%% Local Functions
%%
terminate(Socket) ->
	gen_udp:close(Socket),
	ets:delete(iax_external_peers),
	ets:delete(iax_network_internal_peers),
	ets:delete(iax_dialogs).
